﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Client.Commands;
using Client.Processes;
using Contracts.Entities;

namespace Client.ViewModels.WebImport
{
    /// <summary>
    /// Sucht nach filmen und fügt jedes Ergebnis einer Auflistung hinzu
    /// Wenn die Suche beendet ist, werden die Suchergebnisse an das SearchResultsViewModel weitergeleitet
    /// </summary>
    public class SearchViewModel : WizardPageViewModel
    {
        #region Init

        private IEnumerable<MovieItem> items;
        private SearchMoviesOnline search;
        private List<TmdbSearchResult> results;

        private string log;
        private string info;
        private int resultCount;
        private bool isBusy;
        private bool searchCompleted;

        public SearchViewModel(IEnumerable<MovieItem> items)
        {
            this.search = new SearchMoviesOnline();
            this.results = new List<TmdbSearchResult>();
            this.items = items;

            search.OnResult += OnSearchResult;

            LogMoviesToSearch();
        }

        private void LogMoviesToSearch()
        {
            Log = "Zu folgenden Filmtiteln wird online gesucht: "+ Environment.NewLine + Environment.NewLine;
            
            foreach (var item in items)
                Log += "- " + item.Name + Environment.NewLine;
        } 

        #endregion

        #region Properties

        public string Log
        {
            get
            {
                return log;
            }
            private set
            {
                log = value;
                NotifyPropertyChanged("Log");
            }
        }

        public bool IsBusy
        {
            get
            {
                return isBusy;
            }
            set
            {
                isBusy = value;
                NotifyPropertyChanged("IsBusy");
            }
        }

        public string Info
        {
            get
            {
                return info;
            }
            private set
            {
                info = value;
                NotifyPropertyChanged("Info");
            }
        }

        public ICommand SearchCommand
        {
            get
            {
                return new RelayCommand(() => Search(), () => !isBusy);
            }
        }

        #endregion       

        #region Processes

        private void LogStartInfo()
        {
            var startinfo =
                Environment.NewLine + Environment.NewLine + "Url: " + TmdbApi.Url + Environment.NewLine
                + "Version: " + TmdbApi.Version + Environment.NewLine
                + Environment.NewLine;

            Log += startinfo;
            Info = String.Format("0/{0} Film(e) gesucht", items.Count());
        }

        /// <summary>
        /// Suchergebnis wird der Auflistung hinzugefügt, wenn Suchergebnisse vorhanden
        /// </summary>
        private void OnSearchResult(TmdbSearchResult result)
        {         
            resultCount++;

            Info = String.Format("{0}/{1} Film(e) gesucht", resultCount, items.Count());

            if (result.Success)
            {
                Log += String.Format("{0}: Die Suche nach dem Film \"{1}\" ergab {2} Treffer {3}",
                    DateTime.Now.ToShortTimeString(),
                    result.Request,
                    result.Items.Count(),
                    Environment.NewLine);

                if (result.Items.Count() > 0)
                    results.Add(result);
            }
            else
                Log += String.Format("{0}: Bei der Suche nach dem Film \"{1}\" ist ein Fehler aufgetreten!{2}",
                    DateTime.Now.ToShortTimeString(),
                    result.Request,
                    Environment.NewLine);

            if (resultCount == items.Count())
                SearchCompleted();
        }

        private void Search()
        {
            resultCount = 0;
            IsBusy = true;
            searchCompleted = false;

            LogStartInfo();

            search.Process(items);
        }

        private void SearchCompleted()
        {
            IsBusy = false;
            searchCompleted = true;

            CommandManager.InvalidateRequerySuggested();
            Log += Environment.NewLine;

            OnResult(results);
        }

        #endregion

        #region WebImportBaseViewModel Member

        public override bool IsValid()
        {
            return !isBusy && searchCompleted && results.Count() > 0;
        }

        public override string GetButtonNextContent()
        {
            return "Weiter >>";
        }

        public override void Process(object data)
        {
        }

        public override event Action<object> OnResult; 

        #endregion 
    }
}
